import { tenantId } from '@/utils/request/untils';
import { get, post } from '@/utils/request';
import { getToken } from '@/utils/auth';

const baseUrl = import.meta.env.VITE_APP_BASE_API;

const FileApi = {
  // 上传文件
  uploadFile: (file: string, directory?: AnyObject) => {
    uni.showLoading({
      title: '上传中',
    });
    return new Promise((resolve) => {
      uni.uploadFile({
        url: `${baseUrl}/infra/file/upload`,
        filePath: file,
        name: 'file',
        header: {
          'Accept': '*/*',
          'tenant-id': tenantId,
          'Authorization': getToken(),
        },
        formData: {
          directory,
        },
        success: (uploadFileRes) => {
          const result = JSON.parse(uploadFileRes.data);
          if (result.error === 1) {
            uni.showToast({
              icon: 'none',
              title: result.msg,
            });
          }
          else {
            return resolve(result);
          }
        },
        fail: (error) => {
          console.log('上传失败：', error);
          return resolve(false);
        },
        complete: () => {
          uni.hideLoading();
        },
      });
    });
  },

  // 获取文件预签名地址
  getFilePresignedUrl: (name: string, directory: any) => {
    return get({
      url: '/infra/file/presigned-url',
      params: {
        name,
        directory,
      },
    });
  },

  // 创建文件
  createFile: (data: any) => {
    return post({
      url: '/infra/file/create', // 请求的 URL
      data, // 要发送的数据
    });
  },
};

export default FileApi;
